package com.zqh.irmadscore.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zqh.irmadscore.mapper.SdgChangeMapper;
import com.zqh.irmadscore.model.entity.SdgChange;
import com.zqh.irmadscore.model.entity.SdgFailure;
import com.zqh.irmadscore.service.SdgChangeService;
import com.zqh.irmadscore.service.SdgFailureService;
import lombok.AllArgsConstructor;
import lombok.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@AllArgsConstructor
public class SdgChangeServiceImpl extends ServiceImpl<SdgChangeMapper, SdgChange>
        implements SdgChangeService {


    private final SdgFailureService sdgFailureService;

    @Override
    public List<SdgFailure> setSdgChange(Integer tractId, Integer change) {


        // 参数校验
        if (change > 4 || change < -1) {
//            System.out.println("tractId: " + tractId + ", change: " + change);
            throw new IllegalArgumentException("参数错误：change 必须在 [-1, 3] 范围内");
        }

        // 查询 SdgChange 数据
        LambdaQueryWrapper<SdgChange> sdgChangeQueryWrapper = new LambdaQueryWrapper<>();
        sdgChangeQueryWrapper.eq(SdgChange::getTractId, tractId)
                .eq(SdgChange::getTract_change, change);
        List<SdgChange> sdgChanges = this.list(sdgChangeQueryWrapper);


        // 更新 SdgFailure 的 num 字段
        Map<String, Integer> failureNameToNumMap = new HashMap<>();
        for (SdgChange sdgChange : sdgChanges) {
            String failureName = sdgChange.getFailureName();

            // 查询故障及 num
            LambdaQueryWrapper<SdgFailure> sdgFailureQueryWrapper = new LambdaQueryWrapper<>();
            sdgFailureQueryWrapper.eq(SdgFailure::getFailureName, failureName);
            SdgFailure sdgFailure = sdgFailureService.getOne(sdgFailureQueryWrapper);

            if (ObjectUtil.isEmpty(sdgFailure))
                throw new IllegalStateException("未找到对应的事故：" + failureName);


            failureNameToNumMap.put(failureName, sdgFailure.getNum() + 1);
        }

        // 批量更新 SdgFailure 的 num 字段
        failureNameToNumMap.forEach((failureName, updatedNum) -> {
            LambdaUpdateWrapper<SdgFailure> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(SdgFailure::getFailureName, failureName)
                    .set(SdgFailure::getNum, updatedNum);
            sdgFailureService.update(updateWrapper);
        });

        // 获取更新后的 SdgFailure 列表
        List<SdgFailure> sdgFailureList = sdgFailureService.list();

        // 检查总和是否为 0
        int sumTracts = sdgFailureList.stream()
                .mapToInt(SdgFailure::getNum)
                .sum();

        if (sumTracts == 0) throw new IllegalStateException("监测道为空，无法计算概率");

        // 更新 SdgFailure 的 sumProbability 字段
        for (SdgFailure sdgFailure : sdgFailureList) {
            int num = sdgFailure.getNum();
            double sumProbability = (double) num / sumTracts;

            // 确保概率不超过 1
            if (sumProbability > 1) sumProbability = 1;

            LambdaUpdateWrapper<SdgFailure> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(SdgFailure::getFailureName, sdgFailure.getFailureName())
                    .set(SdgFailure::getSumProbability, sumProbability);
            sdgFailureService.update(updateWrapper);
        }


        var list = sdgFailureService.list().stream()
                .sorted((o1, o2) -> o2.getSumProbability().compareTo(o1.getSumProbability()))
                .collect(Collectors.toList());

        return list;
    }


}
